package cn.edu.scau.disk.exception;

import cn.edu.scau.disk.utils.R;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 用参不合法异常处理器
     * @param e 异常
     * @return 异常信息
     */
    @ExceptionHandler(ParamException.class)
    //@ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleException(ParamException e) {
        return R.fail(e.getMessage());
    }

    /**
     * 常规失败操作
     * @param e
     * @return
     */
    @ExceptionHandler(CommonException.class)
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(CommonException e){
        return R.fail(e.getMessage());
    }

    /**
     * 内部未知错误处理器
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(Exception e){
        return R.fail(e.getMessage());
    }

    /**
     * 入参不合法异常处理器
     * @param e 异常
     * @return 异常信息
     */
    @ExceptionHandler(BindException.class)
    //@ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleException(BindException e) {
        StringBuffer errorMessage = new StringBuffer();
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        errors.forEach(error -> {
            errorMessage.append(error.getDefaultMessage());
        });
        return R.fail(errorMessage.toString());
    }

}
